package com.powernode.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.powernode.constant.Constants;
import com.powernode.entity.Orders;
import com.powernode.service.OrderService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class DelayListener {

    @Resource
    private OrderService orderService;

    /**
     * 监听队列上的消息，只要有消息了，就会调用我们这个onMessage方法
     *
     * @param message
     */
    @RabbitListener(queues = Constants.QUEUE_DELAY_NAME)
    public void onMessage(Message message, Channel channel) {
        String orderId = new String(message.getBody());

//处理业务，如果查询发现订单没有支付，此时就把订单关闭
        Orders orders = orderService.getById(Integer.parseInt(orderId));
        if (orders.getStatus() == 0) { //订单状态 (0待支付， 1已支付，2订单关闭)
            //关闭订单
            UpdateWrapper<Orders> updateWrapper=new UpdateWrapper<>();
            updateWrapper.set("update_time",new Date());
            updateWrapper.set("status",2);
            updateWrapper.eq("id",orders.getId());
//关闭订单，修改成超时未支付
            boolean updateResult = orderService.update(updateWrapper);


            if (updateResult){
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

//手动确认消息，需要写一行代码，提交确认一下
    }
}
